﻿using Application.Instock_hService;
using Application.Outstock_hService;
using Domain.Entity.In;
using Domain.Entity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using System.Text.Json;
using Domain.Entity.Out;
using Application.Instock_dService;
using Application.PublicFileService;
using System.Transactions;
using Application.Outstock_dService;
using Application.CodeRuleService;
using Application.ProductService;
using Application.Purchase_dService;
using Application.Purchase_hService;
using Application.StockService;
using Application.ISale_hService;
using Application.Sale_dService;
using Domain.Entity.ord;
using Application.PurchaseReturn_hService;
using Application.PurchaseReturn_dService;
using Domain.Entity.search;
using WMSManage.Filter;
using Application.Check_dService;
using Application.Check_hService;
using Application.Allot_hService;
using Application.Allot_dService;

namespace WMSManage.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]//需要鉴权
    public class Outstock_hController : ControllerBase
    {
        private readonly IOutstock_hService outstock_HService;
        private readonly IDistributedCache distributedCache;
        private readonly IOutstock_dService outstock_DService;
        private readonly IPublicFileService publicFileService;
        private readonly ISale_hService sale_HService;
        private readonly ISale_dService sale_DService;
        private readonly IProductService productService;
        private readonly ICodeRuleService codeRuleService;
        private readonly IStockService stockService;
        private readonly IPurchaseReturn_hService purchaseReturn_HService;
        private readonly IPurchaseReturn_dService purchaseReturn_DService;
        private readonly IPurchase_hService purchase_HService;
        private readonly IPurchase_dService purchase_DService;
        private readonly ICheck_hService check_HService;
        private readonly ICheck_dService check_DService;
        private readonly IAllot_hService allot_HService;
        private readonly IAllot_dService allot_DService;

        public Outstock_hController(IOutstock_hService outstock_HService,IDistributedCache distributedCache,IOutstock_dService outstock_DService,IPublicFileService publicFileService,ISale_hService sale_HService,ISale_dService sale_DService,IProductService productService,ICodeRuleService codeRuleService,IStockService stockService,
                                    IPurchaseReturn_hService purchaseReturn_HService,IPurchaseReturn_dService purchaseReturn_DService,IPurchase_hService purchase_HService,IPurchase_dService purchase_DService,ICheck_hService check_HService,ICheck_dService check_DService,IAllot_hService allot_HService,IAllot_dService allot_DService)
        {
            this.outstock_HService = outstock_HService;
            this.distributedCache = distributedCache;
            this.outstock_DService = outstock_DService;
            this.publicFileService = publicFileService;
            this.sale_HService = sale_HService;
            this.sale_DService = sale_DService;
            this.productService = productService;
            this.codeRuleService = codeRuleService;
            this.stockService = stockService;
            this.purchaseReturn_HService = purchaseReturn_HService;
            this.purchaseReturn_DService = purchaseReturn_DService;
            this.purchase_HService = purchase_HService;
            this.purchase_DService = purchase_DService;
            this.check_HService = check_HService;
            this.check_DService = check_DService;
            this.allot_HService = allot_HService;
            this.allot_DService = allot_DService;
        }


        /// <summary>
        /// 分页查询出库单
        /// </summary>
        /// <param name="code"></param>
        /// <param name="type"></param>
        /// <param name="status"></param>
        /// <param name="whid"></param>
        /// <param name="CurrentPage"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<FenYe<Outstock_h>> GetOutstock_h(string? code, string? type, int? status, int? whid, int CurrentPage)
        {
            FenYe<Outstock_h> fenYe = new FenYe<Outstock_h>()
            {
                CurrentPage = CurrentPage,
            };
            return await outstock_HService.GetOutstock_h(fenYe, code, type, status, whid);
        }



        /// <summary>
        /// 刷新缓存
        /// </summary>
        /// <param name="code"></param>
        /// <param name="type"></param>
        /// <param name="status"></param>
        /// <param name="whid"></param>
        /// <param name="CurrentPage"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Refresh(string? code, string? type, int? status, int? whid, int CurrentPage)
        {
            //缓存键
            string key = "Outstock_h" + code + type + whid + status + CurrentPage;

            // 清除缓存键
            distributedCache.Remove(key);

            // 返回成功消息
            return Ok(new { success = true, message = "ok" });
        }



        /// <summary>
        /// 高级查询
        /// </summary>
        /// <param name="code"></param>
        /// <param name="starttotal"></param>
        /// <param name="endtotal"></param>
        /// <param name="startdate"></param>
        /// <param name="enddate"></param>
        /// <param name="startnum"></param>
        /// <param name="endnum"></param>
        /// <param name="status"></param>
        /// <param name="type"></param>
        /// <param name="whid"></param>
        /// <param name="createname"></param>
        /// <param name="startcreatetime"></param>
        /// <param name="endcreatetime"></param>
        /// <param name="approvername"></param>
        /// <param name="startapprovertime"></param>
        /// <param name="endapprovertime"></param>
        /// <param name="outuser"></param>
        /// <param name="outorder"></param>
        /// <param name="CurrentPage"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<FenYe<Outstock_h>> GetAdvancedOutstock_h(string? code, string? starttotal, string? endtotal, string? startdate, string? enddate, string? startnum, string? endnum, int? status, string? type, int? whid, string? createname, string? startcreatetime, string? endcreatetime, string? approvername, string? startapprovertime, string? endapprovertime, string? outuser, string? outorder, int CurrentPage)
        {
            FenYe<Outstock_h> fenYe = new FenYe<Outstock_h>()
            {
                CurrentPage = CurrentPage,
            };
            return await outstock_HService.GetAdvancedOutstock_h(fenYe, code, starttotal, endtotal, startdate, enddate, startnum, endnum, status, type, whid, createname, startcreatetime, endcreatetime, approvername, startapprovertime, endapprovertime, outuser, outorder);
        }


        /// <summary>
        /// 出库统计
        /// </summary>
        /// <param name="timeType">时间类型(today,yesterday,week,lastWeek,month,lastMonth)</param>
        /// <param name="code">出库单号</param>
        /// <param name="whid">仓库ID</param>
        /// <param name="instarttime">出库开始时间</param>
        /// <param name="inendtime">出库结束时间</param>
        /// <param name="starttime">开始时间(备用)</param>
        /// <param name="endtime">结束时间(备用)</param>
        /// <param name="outType">出库类型</param>
        /// <param name="page">页码</param>
        /// <param name="pagesize">每页数量</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Outstock_hTJResult> Outstock_hTJ(string? timeType, string? code, int? whid,
            string? instarttime, string? inendtime, string? starttime, string? endtime,
            string? outtype, int? page, int? pagesize)
        {
            //缓存键
            string key = "Outstock_hTJResult" + timeType + code + whid + instarttime + inendtime +
                        starttime + endtime + outtype + page + pagesize;

            //从缓存中获取数据
            var data = await distributedCache.GetStringAsync(key);
            if (data != null)
            {
                //从缓存中查
                return JsonSerializer.Deserialize<Outstock_hTJResult>(data);
            }

          
            //从数据库查
            var result = await outstock_HService.Outstock_hTJ(timeType, code, whid, instarttime,
                inendtime, starttime, endtime, outtype, page, pagesize);

            //将查询到的结果存入缓存
            if (result != null)
            {
                var option = new DistributedCacheEntryOptions
                {
                    AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10) //10分钟缓存
                };
                await distributedCache.SetStringAsync(key, JsonSerializer.Serialize(result), option);
            }
            return result;
        }


        /// <summary>
        /// 出库（创建单据，不影响库存）
        /// </summary>
        /// <param name="payload"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> AddOutstock_h(AddOutstockPayload payload)
        {
            //开启事务
            using var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
            try
            {
                //业务逻辑
                //1.添加主入库单
                var id = await outstock_HService.AddOutstock_h(payload.outstockData);//返回的是当前主键

                //2.添加入库明细
                foreach (var details in payload.outstockDetails)
                {
                    var outstock_d = new Outstock_d
                    {
                        out_id = id,
                        proc_id = details.proc_id,
                        proc_name = details.proc_name,
                        slot_id = details.slot_id,
                        slot_name = details.slot_name,
                        outd_numtotal = details.outd_numtotal,
                        outd_price = details.outd_price,
                        outd_num = details.outd_num,
                        outd_outstockOK_num = details.outd_outstockOK_num,
                        outd_outstockNO_num = details.outd_outstockNO_num,
                        outd_total = details.outd_total,
                        proc_date = details.proc_date,
                        remark = details.remark,
                    };
                    await outstock_DService.AddOutstock_d(outstock_d);
                }

                //3.添加附件
                foreach (var item in payload.attachments)
                {
                    await publicFileService.AddFile(item);
                }
                scope.Complete();//提交事务
                return id; // 返回主入库单ID表示成功
            }
            catch (Exception ex)
            {
                //出错自动回滚
                Console.WriteLine(ex.Message);
                return 0;
            }
        }





        /// <summary>
        /// 出库审核（影响库存，货品，对应单据）
        /// </summary>
        /// <param name="outstockid"></param>
        /// <param name="status"></param>
        /// <param name="approvername"></param>
        /// <param name="approvertime"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<int> ApproverOutstock_h(int outstockid, int status, string approvername, string approvertime)
        {
            if (status == 3)//如果是驳回
            {
                //只改变状态
                return await outstock_HService.UpdateStatus(outstockid, status, approvername, approvertime);
            }

            //通过的话对库存，货品，对应单据，明细做出操作
            //开启事务
            using var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
            try
            {
                //获取出库单及明细
                var outstockHeader = await outstock_HService.GetOutstock_HById(outstockid);
                var outstockDetails = await outstock_DService.GetOutstock_Ds(outstockid);

                //=====根据出库类型执行不同业务逻辑     
                if (outstockHeader.out_type == "销售出库")
                {
                    //更新销售单据出库数及状态
                    //根据关联单号获取到进货单的主键id和总数量
                    var sale_h = await sale_HService.Getid(outstockHeader.out_order);
                    //安全计算：防止出库总量超过销售量
                    int maxAllowOK = (int)(sale_h.sale_num - sale_h.sale_outstockOK_num);
                    int actualOK = Math.Min((int)outstockHeader.out_outstockOK_num, maxAllowOK);
                    int actualNO = (int)outstockHeader.out_outstockOK_num - actualOK;

                    //更新主表
                    int saleid = sale_h.sale_id;
                    int oknum = (int)(sale_h.sale_outstockOK_num + actualOK);
                    int nonum = (int)(sale_h.sale_outstockNO_num + actualNO);
                    int statu = (sale_h.sale_outstockOK_num + actualOK) < sale_h.sale_num ? 8 : 6;
                    await sale_HService.UpdateNum(saleid, oknum, nonum, statu);

                    //更新明细表
                    foreach (var detail in outstockDetails)
                    {
                        //明细id
                        var saledid = await sale_DService.Getid(saleid, detail.proc_id);
                        await sale_DService.UpdateNum(saledid, detail.outd_outstockOK_num, detail.outd_outstockNO_num);
                    }

                    // --- 销售出库的库存更新逻辑 ---
                    //更新货品库存，金额
                    foreach (var detail in outstockDetails)
                    {
                        var updateinventoryDto = new UpdateinventoryDto
                        {
                            proc_id = detail.proc_id,
                            proc_inventory = detail.outd_num, // 本次出库的数量 (增量)
                            proc_ky_inventory = 0,
                            proc_inventory_money = detail.outd_total// 本次出库的金额 (增量)
                        };
                        await productService.UpdateinventoryJian(updateinventoryDto);
                    }

                    //减少库存
                    foreach (var detail in outstockDetails)
                    {
                        var stock = new AddStockDto
                        {
                            stk_code = await codeRuleService.GeneratedCode(18), // 生成新的库存编号
                            wh_id = (int)outstockHeader.wh_id,
                            slot_id = detail.slot_id,
                            proc_id = detail.proc_id,
                            stk_hand_num = (int)detail.outd_num,
                            stk_price = (double)detail.outd_price,
                            stk_total = detail.outd_total,
                            remark = detail.remark
                        };

                        //查询库存
                        var stockdata = await stockService.GetStockByCriteria(stock.proc_id, stock.wh_id, stock.slot_id);
                        //加权平均计算单价
                        double remainingQty = stockdata.stk_hand_num - stock.stk_hand_num;
                        if (remainingQty > 0)
                        {
                            double price = Math.Round((stockdata.stk_total - stock.stk_total) / remainingQty, 2);
                            stock.stk_price = double.IsNaN(price) ? 0 : price;
                        }
                        else
                        {
                            stock.stk_price = 0;
                        }

                        await stockService.UpdateStockJian(stock);
                    }
                }
                else if (outstockHeader.out_type == "退货出库")
                {
                    // --- 1. 获取关联单据 ---
                    var purchaseReturn_h = await purchaseReturn_HService.GetPurchaseReturn_hByCode(outstockHeader.out_order);
                    if (purchaseReturn_h == null) throw new Exception("未找到关联的采购退货单: " + outstockHeader.out_order);

                    var purchase_h = await purchase_HService.GetPurchase_HById(purchaseReturn_h.pur_id);
                    if (purchase_h == null) throw new Exception("未找到采购退货单关联的原始采购单");

                    // --- 2. 更新采购退货单主表 ---
                    int maxAllowOK_purt = (int)(purchaseReturn_h.purt_num - purchaseReturn_h.purt_outstockOK_num);
                    int actualOK_purt = Math.Min((int)outstockHeader.out_outstockOK_num, maxAllowOK_purt);
                    int purtid = purchaseReturn_h.purt_id;
                    int oknum_purt = (int)(purchaseReturn_h.purt_outstockOK_num + actualOK_purt);
                    int nonum_purt = (int)(purchaseReturn_h.purt_outstockNO_num - actualOK_purt); // 未出库数应该减去本次出库数
                    int statu_purt = oknum_purt >= purchaseReturn_h.purt_num ? 6 : 8; // 6:全部出库, 8:部分出库
                    await purchaseReturn_HService.UpdateNum(purtid, oknum_purt, nonum_purt, statu_purt);

                    // --- 3. 更新原始进货单主表 ---
                    int purid = purchase_h.pur_id;
                    int returnnum_pur = (int)(purchase_h.purd_returned_num + actualOK_purt);
                    int rstatu_pur = returnnum_pur >= purchase_h.pur_num ? 11 : 10; // 11:全部退货, 10:部分退货
                    await purchase_HService.UpdateRNum(purid, returnnum_pur, rstatu_pur);

                    // --- 4. 一次性获取所有进货明细，用于后续查找 ---
                    var allPurchaseDetails = await purchase_DService.GetPurchase_Ds(purid);
                    if (allPurchaseDetails == null || !allPurchaseDetails.Any())
                    {
                        throw new Exception("未能获取到原始采购单的任何明细项。");
                    }

                    // --- 5. 循环处理每一条出库明细 ---
                    foreach (var detail in outstockDetails)
                    {
                        var purchase_d_item = allPurchaseDetails.FirstOrDefault(pd => pd.proc_id == detail.proc_id);
                        if (purchase_d_item == null)
                        {
                            Console.WriteLine($"警告：在原始采购单 {purchase_h.pur_code} 中未找到货品ID为 {detail.proc_id} 的明细项。");
                            continue;
                        }

                        // 计算本次应从【物理库存】中扣减的数量
                        int totalInstockedQty = purchase_d_item.purd_instockOK_num;
                        int previouslyReturnedQty = purchase_d_item.purd_returned_num;
                        int maxStockReduction = totalInstockedQty - previouslyReturnedQty;
                        if (maxStockReduction < 0) maxStockReduction = 0;

                        int inventoryReductionQty = Math.Min((int)detail.outd_num, maxStockReduction);

                        // --- 6. 仅当实际需要扣减库存时，才执行库存操作 ---
                        if (inventoryReductionQty > 0)
                        {
                            var updateinventoryDto = new UpdateinventoryDto
                            {
                                proc_id = detail.proc_id,
                                proc_inventory = inventoryReductionQty,
                                proc_ky_inventory = 0,
                                proc_inventory_money = detail.outd_price * inventoryReductionQty
                            };
                            await productService.UpdateinventoryJian(updateinventoryDto);

                            var stock = new AddStockDto
                            {
                                wh_id = (int)outstockHeader.wh_id,
                                slot_id = detail.slot_id,
                                proc_id = detail.proc_id,
                                stk_hand_num = inventoryReductionQty,
                                stk_total = (double)(detail.outd_price * inventoryReductionQty),
                                remark = detail.remark
                            };

                            var stockdata = await stockService.GetStockByCriteria(stock.proc_id, stock.wh_id, stock.slot_id);
                            if (stockdata != null)
                            {
                                double remainingQty = stockdata.stk_hand_num - stock.stk_hand_num;
                                if (remainingQty > 0)
                                {
                                    double newTotalValue = stockdata.stk_total - stock.stk_total;
                                    double price = Math.Round(newTotalValue / remainingQty, 2);
                                    stock.stk_price = double.IsNaN(price) ? 0 : price;
                                }
                                else
                                {
                                    stock.stk_price = 0;
                                }
                                await stockService.UpdateStockJian(stock);
                            }
                        }

                        // --- 7. 更新关联单据的明细状态 ---
                        var purtdid = await purchaseReturn_DService.Getid(purtid, detail.proc_id);
                        await purchaseReturn_DService.UpdateNum(purtdid, detail.outd_outstockOK_num, detail.outd_outstockNO_num);

                        // 【已修正】使用正确的ID来更新原始进货单明细的已退货数量
                        await purchase_DService.UpdateRNum(purchase_d_item.purd_id, detail.outd_outstockOK_num);
                    }
                }
                else if (outstockHeader.out_type == "盘亏出库")
                {
                    // 库存更新逻辑
                    foreach (var detail in outstockDetails)
                    {
                        var updateinventoryDto = new UpdateinventoryDto
                        {
                            proc_id = detail.proc_id,
                            proc_inventory = detail.outd_num, // 本次入库的数量
                            proc_ky_inventory = detail.outd_num, // 期初入库时可用库存等于总库存
                            proc_inventory_money = detail.outd_total
                        };
                        await productService.UpdateinventoryJian(updateinventoryDto);
                    }

                    // 更新仓位库存
                    foreach (var detail in outstockDetails)
                    {
                        var stock = new AddStockDto
                        {
                            stk_code = await codeRuleService.GeneratedCode(18),
                            wh_id = (int)outstockHeader.wh_id,
                            slot_id = detail.slot_id,
                            proc_id = detail.proc_id,
                            stk_hand_num = (int)detail.outd_num,
                            stk_price = (double)detail.outd_price,
                            stk_total = detail.outd_total,
                            remark = detail.remark
                        };

                        var stockdata = await stockService.GetStockByCriteria(stock.proc_id, stock.wh_id, stock.slot_id);
                        if (stockdata == null)
                        {
                            // 没有就添加
                            await stockService.AddStock(stock);
                        }
                        else
                        {
                            // 有就更新，加权平均计算单价
                            double price = Math.Round((stockdata.stk_total + stock.stk_total) / (stockdata.stk_hand_num + stock.stk_hand_num), 2);
                            stock.stk_price = price;
                            await stockService.UpdateStockJian(stock);
                        }
                    }

                    //将修改盘点主单和盘点明细单的入库状态（8：部分出库，6：已完成）
                    if (!string.IsNullOrEmpty(outstockHeader.out_order))
                    {
                        //获取关联的盘点单ID
                        int icid = await check_HService.Getid(outstockHeader.out_order);
                        //名称
                        string name = "outstock_status";
                        //更新盘点单的入库状态
                        await check_HService.UpdateStatus(name, 6, icid);
                        foreach (var detail in outstockDetails)
                        {
                            await check_DService.UpdateStatus(name, 6, icid, detail.proc_id);
                        }
                    }
                }
                else if (outstockHeader.out_type == "调拨出库")
                {
                    // 更新仓位库存
                    foreach (var detail in outstockDetails)
                    {
                        var stock = new AddStockDto
                        {
                            stk_code = await codeRuleService.GeneratedCode(18),
                            wh_id = (int)outstockHeader.wh_id,
                            slot_id = detail.slot_id,
                            proc_id = detail.proc_id,
                            stk_hand_num = (int)detail.outd_num,
                            stk_price = (double)detail.outd_price,
                            stk_total = detail.outd_total,
                            remark = detail.remark
                        };

                        var stockdata = await stockService.GetStockByCriteria(stock.proc_id, stock.wh_id, stock.slot_id);
                        if (stockdata == null)
                        {
                            // 没有就添加
                            await stockService.AddStock(stock);
                        }
                        else
                        {
                            // 有就更新，加权平均计算单价
                            double price = Math.Round((stockdata.stk_total + stock.stk_total) / (stockdata.stk_hand_num + stock.stk_hand_num), 2);
                            stock.stk_price = price;
                            await stockService.UpdateStockJian(stock);
                        }
                    }

                    //将修改调拨单的入库状态
                    if (!string.IsNullOrEmpty(outstockHeader.out_order))
                    {
                        //获取关联的调拨单ID
                        int alid = await allot_HService.Getid(outstockHeader.out_order);
                        //名称
                        string name = "outstock_status";
                        string nameok = "al_outstockOK_num";
                        string nameno = "al_outstockNO_num";
                        string nameokd = "ald_outstockOK_num";
                        string namenod = "ald_outstockNO_num";
                        //更新盘点单的入库状态
                        await allot_HService.UpdateStatus(nameok, (int)outstockHeader.out_outstockOK_num, nameno, (int)outstockHeader.out_outstockNO_num, name, alid);
                        foreach (var detail in outstockDetails)
                        {
                            await allot_DService.UpdateStatus(nameokd, (int)detail.outd_outstockOK_num, namenod, (int)detail.outd_outstockNO_num, name, alid, detail.proc_id);
                        }
                    }
                }

                //最后修改出库单状态
                await outstock_HService.UpdateStatus(outstockid, status, approvername, approvertime);
                scope.Complete();//提交事务
                return 1;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                // 事务会自动回滚
                return 0;
            }
        }




        /// <summary>
        /// 根据id查询出库单
        /// </summary>
        /// <param name="outstockid"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Outstock_h> GetOutstock_HById(int outstockid)
        {
            return await outstock_HService.GetOutstock_HById(outstockid);
        }



        /// <summary>
        /// 删除出库单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<int> DeleteOutstock_h(int id)
        {
            return await outstock_HService.DeleteOutstock_h(id);
        }



        /// <summary>
        /// 修改单据状态
        /// </summary>
        /// <param name="outstockid"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<int> UpdateStatus(int outstockid, int status)
        {
            return await outstock_HService.UpdateStatus(outstockid,status);
        }




        /// <summary>
        /// 修改出库单(不影响库存)
        /// </summary>
        /// <param name="updateOutstockPayload"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> UpdateOutstock_h(UpdateOutstockPayload updateOutstockPayload)
        {
            //开启事务
            using var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
            try
            {
                //1.修改主出库单
                await outstock_HService.UpdateOutstock_h(updateOutstockPayload.outstockData);

                //2.修改出库明细
                //2.1获取所有旧明细
                var oldDetails = await outstock_DService.GetOutstock_Ds(updateOutstockPayload.outstockData.out_id);
                var oldDetailsIds = oldDetails.Select(d => d.outd_id).ToList();//所有旧明细的主键id
                //2.2从前端提交的数据中获取到新的明细
                var newDetails = updateOutstockPayload.outstockDetails;
                var newDetailsIds = newDetails.Where(d => d.outd_id > 0).Select(d => d.outd_id).ToList();//所有新明细的主键id
                //2.3新id和旧id看久id有没有多出来的有的话就删除
                var idsToDelete = oldDetailsIds.Except(newDetailsIds).ToList();
                if (idsToDelete.Any())
                {
                    foreach (var id in idsToDelete)
                    {
                        //删掉
                        await outstock_DService.DeleteOutstock_d(id);
                    }
                }
                //2.4遍历所有明细,进行新增或修改
                var detailsToAdd = new List<Outstock_d>();
                var detailsToUpdate = new List<Outstock_d>();
                foreach (var detail in updateOutstockPayload.outstockDetails)
                {
                    if (detail.outd_id > 0)
                    {
                        detailsToUpdate.Add(detail);//改
                    }
                    else
                    {
                        detail.out_id = updateOutstockPayload.outstockData.out_id;
                        detailsToAdd.Add(detail);//增
                    }
                }
                if (detailsToUpdate.Any())
                {
                    foreach (var item in detailsToUpdate)
                    {
                        await outstock_DService.UpdateOutstock_d(item);
                    }
                }
                if (detailsToAdd.Any())
                {
                    foreach (var item in detailsToAdd)
                    {
                        await outstock_DService.AddOutstock_d(item);
                    }
                }


                //3.修改附件
                //获取附件
                var filelist = updateOutstockPayload.attachments;
                //先删除
                foreach (var item in filelist)
                {
                    await publicFileService.DeleteFile(item.business_type, item.business_code);
                }
                //在添加
                foreach (var item in filelist)
                {
                    await publicFileService.AddFile(item);
                }
                scope.Complete();//提交事务
                return 1;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return 0;
            }
        }



        /// <summary>
        /// 根据货品id查询出库记录
        /// </summary>
        /// <param name="procid"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<Outstock_h>> GetAllOutstock_h(int procid)
        {
            return await outstock_HService.GetAllOutstock_h(procid);
        }


        /// <summary>
        /// 根据关联单号查询出库记录
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<Outstock_h>> GetAllOutstock_hByCode(string code)
        {
            return await outstock_HService.GetAllOutstock_hByCode(code);
        }

        /// <summary>
        /// 通过供应商ID查
        /// </summary>
        /// <param name="CurrentPage"></param>
        /// <param name="sup_id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<FenYe<Outstock_h>> GetOutstock_hSup(int CurrentPage, int sup_id)
        {
            FenYe<Outstock_h> fenYe = new FenYe<Outstock_h>()
            {
                CurrentPage = CurrentPage,
            };
            return await outstock_HService.GetOutstock_hSup(fenYe, sup_id);
        }

        /// <summary>
        /// 通过客户ID查
        /// </summary>
        /// <param name="CurrentPage"></param>
        /// <param name="cust_id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<FenYe<Outstock_h>> GetOutstock_hCust(int CurrentPage, int cust_id)
        {
            FenYe<Outstock_h> fenYe = new FenYe<Outstock_h>()
            {
                CurrentPage = CurrentPage,
            };
            return await outstock_HService.GetOutstock_hCust(fenYe, cust_id);
        }
    }
}
